/**
 * @Copyright ®2015 Sinosoft Co. Ltd. All rights reserved.<br/>
 * 项目名称 : 中科软支付平台
 * 创建日期 : 2017年2月16日
 * 修改历史 : 
 *     1. [2017年2月16日]创建文件 by liuyujia
 */
package com.sinosoft.sinopay.web.agentpay.web.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.sinocloud.platform.base.SinoBaseController;
import com.sinosoft.sinocloud.platform.common.exception.biz.SinoBizException;
import com.sinosoft.sinopay.api.common.dto.pay.PaymentInfoDetailDTO;
import com.sinosoft.sinopay.web.agentpay.biz.config.ENUM_REPORT_NOTIFYTYPE;
import com.sinosoft.sinopay.web.agentpay.biz.service.AgentSecurityService;
import com.sinosoft.sinopay.web.agentpay.biz.service.PaymentAgentService;
import com.sinosoft.sinopay.web.agentpay.dto.TongPageReturnNotifyDTO;
import com.sinosoft.sinopay.web.util.AmountTransUtil;
import com.sinosoft.sinopay.web.util.Base64;

/**  
 * 【代理网关支付页面回调请求Controller】
 * @author liuyujia
 * @date 2017年2月16日 下午5:11:02 
 * @version V1.0  
 */
@Controller
@RequestMapping("/sinopay/agentPageReturn")
public class AgentPayPageReturnUrlController extends SinoBaseController{
	@Autowired
	private AgentSecurityService agentSecurityService;
	@Autowired
	private PaymentAgentService paymentAgentService;
	
	@RequestMapping(value = "pageNotify.do")
	public String returnRrl(HttpServletRequest request, HttpServletResponse response){
		logger.info("接收到统统付页面回调start...");
		AmountTransUtil amountTransUtil=  new AmountTransUtil();
		try{
			//1.接收页面回调参数
			byte[] resByte = Base64.decode((String) request.getParameter("res"));
			//2.转JSON格式
			String json = new String(resByte,"UTF-8");
		    logger.info("页面回调信息为："+json);
		    TongPageReturnNotifyDTO tongPageReturnNotifyDTO = JSONObject.parseObject(json, TongPageReturnNotifyDTO.class);
		    //3.获取商盟统统付的通知返回参数
		    //商户订单号
		    String order_no = tongPageReturnNotifyDTO.getOrder_no();
		    //交易状态
		    String status =tongPageReturnNotifyDTO.getStatus();
		    //返回结果码
		    String resp_code = tongPageReturnNotifyDTO.getResp_code();
		    //4.计算得出通知验证结果
		    boolean verify_result = agentSecurityService.checkReturnInfoVerify(tongPageReturnNotifyDTO);
		    if(verify_result){
			    //验证成功,判断支付号是否为支付平台号码
				PaymentInfoDetailDTO tPaymentInfoDetailDTO = paymentAgentService.getPaymentTradeForPayNo(order_no);
		    	//验证金额
				if(tPaymentInfoDetailDTO.getPayAmount()==null && "".equals(tPaymentInfoDetailDTO.getPayAmount())){
					throw new Exception("支付金额不正确");
				}
				String money = amountTransUtil.fenToYuan(tPaymentInfoDetailDTO.getPayAmount());
					if(tongPageReturnNotifyDTO.getSucc_amt().equals(money)){
				    	logger.info("支付金额正确");
				    }
				    else{
				    	throw new Exception("支付金额不正确");
				    }
					String returnCode = null;
			        if(resp_code.equals("000000")&&status.equals("1")){
			        	returnCode = "SUCCESS";
		        	}
		        	else{
		        		returnCode = "FAIL";
		        	}
			      //5.存日志表
			        
			      //6.根据商户编码找到页面回调地址
				  String tMerchantCode = tPaymentInfoDetailDTO.getMerchantCode();
				  logger.info("商户为:"+tMerchantCode);
				  String tNotifyUrl = paymentAgentService.getNotifyUrlByMerchant(tMerchantCode, ENUM_REPORT_NOTIFYTYPE.PAGE_NOTIFY.code());
				  logger.info("商户："+tMerchantCode+"的页面回调地址为："+tNotifyUrl);
			      //7.结果转换成map
		          Map <String ,String > map = new HashMap<String ,String>();  
		          map.put("returnCode", returnCode);
		          map.put("payNo", order_no);
		          map.put("payAmount", money);
		          map.put("notifyUrl", tNotifyUrl);
		          logger.info("payNo="+order_no+"payAmount="+tongPageReturnNotifyDTO.getSucc_amt());
		          request.setAttribute("map", map);
				}
				else{
			    	throw new Exception("回调验签不通过");
			    }
		}
		catch (UnsupportedEncodingException e) {
			logger.info("json格式转换失败");
			e.printStackTrace();
		}catch(SinoBizException sex){
			logger.info("没有查询到相关支付信息");
			sex.printStackTrace();
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		return "/page/agent/agentNotify.jsp";
	}
}
